import 'dart:async';
import 'dart:math';

import 'package:get/get.dart';
import 'package:largefriends/config/lf_route.dart';
import 'package:largefriends/entity/entities/lf_album_entity.dart';
import 'package:largefriends/entity/entities/lf_photo_entity.dart';
import 'package:largefriends/service/lf_auth_service.dart';

import '../../../events/user_change_event.dart';
import '../../../service/manager/lf_event_helper.dart';
import '../../../net/error_handle.dart';
import '../../../net/lf_api_url.dart';
import '../../../net/lf_dio_util.dart';
import '../../../net/lf_image_upload.dart';
import '../../../utils/lf_dialog_utils.dart';
import '../../../widgets/lf_image_picker.dart';

enum PhotoType {
  public,
  private,
}

toManagePhotos({required PhotoType photoType}) {
  Get.toNamed(LFRoute.pathManagePhoto, arguments: {'type': photoType});
}

class LfManagePhotosLogic extends GetxController {
  var type = PhotoType.public;
  LfAuthService authService = Get.find();

  List<LfPhotoEntity> publicPhotos = List.empty(growable: true);
  List<LfPhotoEntity> privatePhotos = List.empty(growable: true);

  late StreamSubscription<UserChangeEvent> _subscription;

  @override
  void onInit() {
    type = Get.arguments['type'];
    publicPhotos.addAll(authService.currentAccount!.publicPhotos());
    privatePhotos.addAll(authService.currentAccount!.privatePhotos());
    super.onInit();
    _subscription =
        LfEventHelper().getEvent().on<UserChangeEvent>().listen((event) {
      publicPhotos.clear();
      privatePhotos.clear();
      publicPhotos.addAll(authService.currentAccount!.photos ?? []);
      privatePhotos.addAll(authService.currentAccount!.privatePhotos());
      update();
    });
  }

  @override
  void onClose() {
    _subscription.cancel();
    super.onClose();
  }

  sortPublicPhoto({bool isChangeAvatar = false}) {
    List<String> attachIds = List.empty(growable: true);
    for (var element in publicPhotos) {
      if (element.attachId != null) {
        attachIds.add(element.attachId!);
      }
    }
    var params = 'type=1&attachIds=${attachIds.join(',')}';
    LfDio.instance
        .post<LfAlbumEntity>(
      url: apiSortPhotos,
      params: params,
    )
        .then((value) {
      authService.currentAccount!.photos = value.photos;
      authService.currentAccount!.avatar = value.photos?.first.url;
      publicPhotos.clear();
      publicPhotos.addAll(authService.currentAccount!.publicPhotos());
      authService.setUserEntity(authService.currentAccount);
    }, onError: (error) {
      if (error is NetError) {
        showSnackBar(error.msg);
      }
      publicPhotos.clear();
      publicPhotos.addAll(authService.currentAccount!.publicPhotos());
      update();
    });
  }

  sortPrivatePhoto() {
    List<String> attachIds = List.empty(growable: true);
    for (var element in privatePhotos) {
      if (element.attachId != null) {
        attachIds.add(element.attachId!);
      }
    }
    var params = 'type=2&attachIds=${attachIds.join(',')}';
    LfDio.instance
        .post<LfAlbumEntity>(
      url: apiSortPhotos,
      params: params,
    )
        .then((value) {
      authService.currentAccount!.privateAlbum = value.photos;
      privatePhotos.clear();
      privatePhotos.addAll(authService.currentAccount!.privatePhotos());
      authService.setUserEntity(authService.currentAccount);
    }, onError: (error) {
      if (error is NetError) {
        showSnackBar(error.msg);
      }
      privatePhotos.clear();
      privatePhotos.addAll(authService.currentAccount!.privatePhotos());
      update();
    });
  }

  addPublicPhotos() {
    _addPhotosAction(photoTypePublic);
  }

  addPrivatePhotos() {
    _addPhotosAction(photoTypePrivate);
  }

  _addPhotosAction(int type) {
    var maxLength = 1;
    if (type == photoTypePublic) {
      maxLength = min(6, 26 - publicPhotos.length);
    } else if (type == photoTypePrivate) {
      maxLength = min(6, 26 - privatePhotos.length);
    } else {
      return;
    }
    if (maxLength == 0) {
      return;
    }
    LfImagePicker.pickerImage(
      (result) async {
        if (result.isEmpty) {
          return;
        }
        showLoading();
        await uploadPicture(fileList: result, type: type).then((attaches) {
          if (attaches.isEmpty) {
            hideLoading();
            return;
          }
          if (type == photoTypePublic) {
            authService.currentAccount!.publicPhotos().addAll(attaches);
            authService.setUserEntity(authService.currentAccount);
            publicPhotos.clear();
            publicPhotos.addAll(authService.currentAccount!.publicPhotos());
          } else if (type == photoTypePrivate) {
            for (var element in attaches) {
              element.type = photoTypePrivate;
              authService.currentAccount!.privatePhotos().add(element);
            }
            authService.setUserEntity(authService.currentAccount);
            privatePhotos.clear();
            privatePhotos.addAll(authService.currentAccount!.privatePhotos());
          }
          hideLoading();
        }, onError: (error) {
          hideLoading();
          if (error is NetError) {
            showSnackBar(error.msg);
          }
        });
      },
      maxCount: maxLength,
    );
  }
}
